package com.kyxx.topics.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.activity.DetailActivity;
import com.kyxx.topics.activity.DetailAdvertiseActivity;
import com.kyxx.topics.activity.DetailQuanActivity;
import com.kyxx.topics.activity.DetailVideoActivity;
import com.kyxx.topics.bean.ArticleBean;
import com.kyxx.topics.bean.TagBean;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.Constants;
import com.kyxx.topics.utils.SettingUtils;
import com.kyxx.topics.utils.StringUtil;
import com.kyxx.topics.utils.TextUtil;
import com.kyxx.topics.utils.TimeUtils;
import com.kyxx.topics.widget.HeaderViewPagerFragment;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.request.BaseRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.wang.avi.AVLoadingIndicatorView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.Call;
import okhttp3.Response;

public class NewsFragmentNew extends HeaderViewPagerFragment {
    private View contentView = null;
    private ListView lv;
    private Context context;
    private TagBean tagBean;
    private int lastVisiblePosition;
    private RelativeLayout rl_progress;
    private ProgressBar avi;
    private LinearLayout ll_reload;
    private List<ArticleBean> articleBeanList = new ArrayList<>();
    private ZhuanTiAdapter zhuanTiAdapter;
    private int pageSize = 1;
    private int countSize = 20;
    private SettingUtils settingUtils = new SettingUtils();
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
            .cacheOnDisk(true)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .showImageOnFail(R.mipmap.image_default)
            .showImageOnLoading(R.mipmap.image_default)
            .showImageForEmptyUri(R.mipmap.image_default)
            .build();
    private Handler parentHandler;
    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    rl_progress.setVisibility(View.GONE);
                    break;
                case 2:
                    switch (msg.arg1) {
                        case Constants.INITDATA:
                            if (rl_progress != null)
                                rl_progress.setVisibility(View.VISIBLE);
                            if (avi != null)
                                avi.setVisibility(View.GONE);
                            if (ll_reload != null)
                                ll_reload.setVisibility(View.VISIBLE);
                            break;
                        case Constants.REFRESH:
                            pageSize=1;
                            if (rl_progress != null)
                                rl_progress.setVisibility(View.VISIBLE);
                            if (avi != null)
                                avi.setVisibility(View.GONE);
                            if (ll_reload != null)
                                ll_reload.setVisibility(View.VISIBLE);
                            break;
                        default:
                            if (rl_progress != null)
                                rl_progress.setVisibility(View.GONE);
                            break;
                    }
                    break;
                case 3:
                    switch (msg.arg1) {
                        case Constants.INITDATA:
                            if (rl_progress != null)
                                rl_progress.setVisibility(View.VISIBLE);
                            if (avi != null)
                                avi.setVisibility(View.VISIBLE);
                            if (ll_reload != null)
                                ll_reload.setVisibility(View.GONE);
                            break;
                        case Constants.REFRESH:
                            pageSize = 1;
                            if (rl_progress != null)
                                rl_progress.setVisibility(View.GONE);
                            if (avi != null)
                                avi.setVisibility(View.VISIBLE);
                            if (ll_reload != null)
                                ll_reload.setVisibility(View.GONE);
                            break;
                        default:
                            if (rl_progress != null)
                                rl_progress.setVisibility(View.GONE);
                            break;
                    }
                    break;

            }
        }
    };

    public static NewsFragmentNew newInstace(Bundle args) {
        NewsFragmentNew f = new NewsFragmentNew();
        f.setArguments(args);
        return f;
    }

    @Override
    public View getScrollableView() {
        return lv;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("tag", tagBean);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (zhuanTiAdapter != null) {
            zhuanTiAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (contentView == null) {
            contentView = inflater.inflate(R.layout.fragment_news_new, container, false);
        } else {
            return contentView;
        }
        return contentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (view == null)
            return;
        Bundle bundle = getArguments();
        tagBean = (TagBean) bundle.getSerializable("tagBean");
        if (savedInstanceState != null) {
            tagBean = (TagBean) savedInstanceState.get("tag");
        }
        context = getActivity();
        rl_progress = (RelativeLayout) view.findViewById(R.id.rl_progress);
        avi = (ProgressBar) view.findViewById(R.id.avi);
        ll_reload = (LinearLayout) view.findViewById(R.id.ll_reload);
        lv = (ListView) view.findViewById(R.id.lv);
        zhuanTiAdapter = new ZhuanTiAdapter();
        lv.setAdapter(zhuanTiAdapter);
        pageSize = 1;
        initList(Constants.INITDATA, pageSize, countSize);
        ll_reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pageSize = 1;
                initList(Constants.INITDATA, pageSize, countSize);
            }
        });
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (articleBeanList.get(i).getVideo() != null) {
                    Intent intent = new Intent(context, DetailVideoActivity.class);
                    intent.putExtra("title", articleBeanList.get(i).getTitle());
                    intent.putExtra("id", articleBeanList.get(i).getId());
                    if (articleBeanList.get(i).getImgurl() == null) {
                        intent.putExtra("imageUrl", "");
                    } else {
                        intent.putExtra("imageUrl", UrlUtils.BASEHTTP + articleBeanList.get(i).getImgurl().getPath());
                    }
                    intent.putExtra("videoUrl", articleBeanList.get(i).getVideo());
                    intent.putExtra("fav_position", i);
                    startActivityForResult(intent, 0);
                    addBrowseLog(articleBeanList.get(i).getId());
                    return;
                }
                if (articleBeanList.get(i).getType() == 4) {
                    Intent intent = new Intent(context, DetailQuanActivity.class);
                    intent.putExtra("title", articleBeanList.get(i).getTitle());
                    intent.putExtra("id", articleBeanList.get(i).getId());
                    startActivity(intent);
                } else if (articleBeanList.get(i).getType() == 5) {
                    Intent intent = new Intent(context, DetailAdvertiseActivity.class);
                    intent.putExtra("title", articleBeanList.get(i).getTitle());
                    intent.putExtra("id", articleBeanList.get(i).getId());
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(context, DetailActivity.class);
                    intent.putExtra("title", articleBeanList.get(i).getTitle());
                    intent.putExtra("id", articleBeanList.get(i).getId());
                    startActivity(intent);
                }
                addBrowseLog(articleBeanList.get(i).getId());
            }
        });
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                if (lastVisiblePosition == lv.getLastVisiblePosition())
                    return;
                lastVisiblePosition = lv.getLastVisiblePosition();
                Log.e("topic", lastVisiblePosition + "onScroll" + lv.getCount());
                if (lastVisiblePosition == lv.getCount() - 2 && lv.getCount() >= countSize) {
                    pageSize++;
                    initList(Constants.LOADMORE, pageSize, countSize);
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        if (contentView != null)
            ((ViewGroup) contentView.getParent()).removeView(contentView);
        super.onDestroyView();
    }

    class ZhuanTiAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return articleBeanList.size();
        }

        @Override
        public Object getItem(int i) {
            return articleBeanList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = View.inflate(context, R.layout.item_zhuanti, null);
                holder.iv_zhuanti = (ImageView) view.findViewById(R.id.iv_zhuanti);
                holder.tv_title = (TextView) view.findViewById(R.id.tv_title);
                holder.tv_day = (TextView) view.findViewById(R.id.tv_day);
                holder.iv_focus = (ImageView) view.findViewById(R.id.iv_focus);
                holder.tv_num = (TextView) view.findViewById(R.id.tv_num);
                holder.tv_type = (TextView) view.findViewById(R.id.tv_type);
                holder.tv_read_num = (TextView) view.findViewById(R.id.tv_read_num);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            switch (settingUtils.getZiTiDaXiao()) {
                case 0:
                    holder.tv_title.setTextSize(13);
                    break;
                case 1:
                    holder.tv_title.setTextSize(17);
                    break;
                case 2:
                    holder.tv_title.setTextSize(21);
                    break;
            }
            if (articleBeanList.get(i).getImgurl() != null) {
                imageLoader.displayImage(UrlUtils.BASEHTTP + articleBeanList.get(i).getImgurl().getPath(), holder.iv_zhuanti, options);
            } else {
                imageLoader.displayImage("", holder.iv_zhuanti, options);
            }
            if (articleBeanList.get(i).getType() == 4) {
                holder.tv_type.setText("优惠券");
                holder.tv_type.setVisibility(View.VISIBLE);
            } else if (articleBeanList.get(i).getType() == 5) {
                holder.tv_type.setText("广告");
                holder.tv_type.setVisibility(View.VISIBLE);
            } else {
                holder.tv_type.setText("");
                holder.tv_type.setVisibility(View.GONE);
            }
            holder.tv_title.setText(Html.fromHtml(articleBeanList.get(i).getTitle()));
            holder.tv_day.setText(TimeUtils.milliseconds2String(Long.valueOf(articleBeanList.get(i).getCreate_time()) * 1000, new SimpleDateFormat("MM-dd HH:mm")));
            holder.tv_num.setText(articleBeanList.get(i).getComment());
            holder.tv_read_num.setText(StringUtil.numberFormat(articleBeanList.get(i).getView()));
            return view;
        }
    }

    class ViewHolder {
        private ImageView iv_zhuanti;
        private TextView tv_title;
        private TextView tv_day;
        private ImageView iv_focus;
        private TextView tv_num;
        private TextView tv_type;
        private TextView tv_read_num;
    }

    public void initList(final int type, int page, int count) {
        if (tagBean == null) {
            return;
        }
        String cachekey = "list&cat=" + tagBean.getId() + "&p=" + page + "&rows=" + count;
        OkGoRequest.get(UrlUtils.LISTS + "&cat=" + tagBean.getId() + "&p=" + page + "&rows=" + count, getActivity(), cachekey, CacheMode.REQUEST_FAILED_READ_CACHE, new StringCallback() {
            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                Message msg = new Message();
                msg.what = 3;
                msg.arg1 = type;
                switch (type) {
                    case Constants.INITDATA:
                        handler.sendMessageDelayed(msg, Constants.DELAYTIMES);
                        break;
                    case Constants.REFRESH:
                        handler.sendMessageDelayed(msg, Constants.DELAYTIMES);
                        break;
                    default:
                        handler.sendMessageDelayed(msg, Constants.DELAYTIMES);
                        break;
                }
            }

            @Override
            public void onAfter(@Nullable String s, @Nullable Exception e) {
                super.onAfter(s, e);
                if (parentHandler != null)
                    parentHandler.sendEmptyMessage(Constants.REFRESH);
            }

            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onCacheError(Call call, Exception e) {
                super.onCacheError(call, e);
                Message msg = new Message();
                msg.what = 2;
                msg.arg1 = type;
                handler.sendMessageDelayed(msg, Constants.DELAYTIMES);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                handler.sendEmptyMessageDelayed(0, Constants.DELAYTIMES);
                try {
                    JSONObject result = new JSONObject(s);
                    switch (type) {
                        case Constants.INITDATA:
                            articleBeanList = JSON.parseArray(result.getJSONArray("data").toString(), ArticleBean.class);
                            zhuanTiAdapter = new ZhuanTiAdapter();
                            lv.setAdapter(zhuanTiAdapter);
                            break;
                        case Constants.LOADMORE:
                            articleBeanList.addAll(JSON.parseArray(result.getJSONArray("data").toString(), ArticleBean.class));
                            zhuanTiAdapter.notifyDataSetChanged();
                            break;
                        case Constants.REFRESH:
                            articleBeanList = JSON.parseArray(result.getJSONArray("data").toString(), ArticleBean.class);
                            zhuanTiAdapter = new ZhuanTiAdapter();
                            lv.setAdapter(zhuanTiAdapter);
                            break;
                    }
                    lastVisiblePosition = lv.getLastVisiblePosition();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void setValue(TagBean tagBean) {
        this.tagBean = tagBean;
    }

    public TagBean getValue() {
        return this.tagBean;
    }

    public void setHandler(Handler handler) {
        this.parentHandler = handler;
    }

    private void addBrowseLog(String id) {
        if (TextUtils.isEmpty(BaseApp.getModel().getId()))
            return;
        HttpParams params = new HttpParams();
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        jsonObject.put("uid", BaseApp.getModel().getId());
        jsonObject.put("news_id", id);
        params.put("json", jsonObject.toString());
        OkGoRequest.post(UrlUtils.addBrowseLog, getActivity(), "addBrowseLog", CacheMode.NO_CACHE, params, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {

            }
        });
    }
}
